<template>
  <div class="ExamViewMain">
    <div class="logo" v-if="isLogo">
      <img :src="examLogo" alt="" />
    </div>
    <div v-if="isOvertime === '0' && isHasAnswer === '1'" class="overTimeClass">
      <div class="module">
        <h2>
          {{ examConfig.testName }}
        </h2>
        <div class="fontSize13">
          {{ examConfig.startTime }}&nbsp;至&nbsp;{{ examConfig.endTime }}
        </div>
        <h1>考试已结束</h1>
        <!-- <div>
          <el-button type="primary">返回</el-button>
        </div> -->
      </div>
    </div>
    <template v-else>
      <template v-if="isStart">
        <div
          class="examDataAdd qsgMain ExamViewBody"
          v-if="isOvertime === '1' && !isThank"
        >
          <div class="examTop">
            <div style="display: flex; align-items: center">
              <img
                :src="titleImg"
                alt=""
                style="width: 80px; margin-top: -3px"
              />
              <div
                style="
                  margin: 0px 10px;
                  height: 25px;
                  border-left: 1px solid #fff;
                "
              ></div>
              <template v-if="examConfig.testName.length > 30">
                <el-tooltip
                  class="item"
                  effect="light"
                  :content="examConfig.testName"
                  placement="top-start"
                >
                  <span>{{ examConfig.testName.substring(0, 30) }}...</span>
                </el-tooltip>
              </template>
              <template v-else>
                {{ examConfig.testName }}
              </template>
              <div style="color: #ccc">(系统每5分钟自动保存试卷)</div>
            </div>
            <div class="ExamViewBtn" v-if="!isThank">
              <div class="blockStyle">用户名：{{ realName }}</div>
              <div class="examUseTime blockStyle" v-if="type === 'add'">
                {{ time }}
              </div>
              <!-- 空白试卷提交时接口返回错误，暂时不能提交空白试卷 -->
              <el-button
                :loading="loadingBtn"
                style="background-color: #1db6a0"
                size="small"
                type="primary"
                v-if="type === 'add'"
                :disabled="examConfig.subjectNum == 0"
                @click.stop="examSave(false)"
                >提交试卷</el-button
              >
            </div>
          </div>
          <div class="examContent">
            <div class="left">
              <div class="answerSheet">
                <div style="color: black; margin-bottom: 20px">
                  <div style="font-weight: 700; line-height: 45px">答题卡</div>
                  <div style="color: #9597a0">
                    共{{ examConfig.subjectNum }}题&nbsp;合计{{
                      examConfig.totalScore
                    }}分
                  </div>
                </div>
                <div class="sheetContent">
                  <template v-for="(column, index) in examFormOption.column">
                    <div
                      :key="index"
                      class="indexStyle"
                      :style="
                        column.isActive
                          ? 'background-color: #3ad3bd;color:#fff;'
                          : 'background-color: #f4f5f7;color:#c7cad3'
                      "
                      v-if="column.typeExam !== 'htmlExam'"
                      v-html="resetIndexFun(column.prop, examFormOption.column)"
                      @click.stop="sheetClick(column.prop)"
                    ></div>
                  </template>
                </div>
                <hr />
                <div class="colorContent">
                  <div>
                    <div
                      class="colorBlock"
                      style="background-color: #3ad3bd"
                    ></div>
                    <span>已做</span>
                  </div>
                  <!-- <div>
                <div class="colorBlock" style="background-color: #ffbc7d"></div>
                <span>当前</span>
              </div> -->
                  <div>
                    <div
                      class="colorBlock"
                      style="background-color: #f4f5f7"
                    ></div>
                    <span>未做</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="right">
              <div
                class="ExamView"
                id="ExamViewRightMain"
                v-if="examConfig.subjectNum > 0"
              >
                <ExamViewCom
                  ref="examFormRef"
                  :data="examFormData"
                  :option="examFormOption"
                  :examConfig="examConfig"
                  :key="examFormKey"
                  :showTime="true"
                  :isDetail="isDetail"
                  @formChange="formChange"
                >
                </ExamViewCom>
              </div>
              <div class="employe" v-else>
                <img
                  class="employeImg"
                  src="@/assets/iconfont/employe.png"
                  alt=""
                />
                <div>暂无数据</div>
              </div>
            </div>
          </div>
          <div class="cusSet">
            <div v-if="captchaTag">
              <el-form
                :model="captchaForm"
                class="captchaForm"
                ref="captchaRef"
              >
                <el-form-item
                  class="captchaItem"
                  prop="captchaValue"
                  label="验证码"
                  label-width="120px"
                  :rules="[
                    {
                      required: true,
                      message: '请输入验证码',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <div class="captchaContent">
                    <el-input
                      v-model="captchaForm.captchaValue"
                      class="captchaInput"
                      size="small"
                    ></el-input>
                    <div class="captchaRight">
                      <img
                        :src="captchaImg"
                        @click.stop="getCaptcha"
                        class="captchaImg"
                      />
                      <el-link
                        type="primary"
                        @click.stop="getCaptcha"
                        :underline="false"
                        class="captchaChange"
                        >(换一个)</el-link
                      >
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        <div class="overTimeClass" v-if="isThank">
          <div class="module">
            <h2>
              {{ examConfig.testName }}
            </h2>
            <div class="fontSize13">
              {{ examConfig.startTime }}&nbsp;至&nbsp;{{ examConfig.endTime }}
            </div>
            <h2>{{ examConfig.thankWord }}</h2>
            <div>
              <el-button
                type="primary"
                v-if="examConfig.limitNum === 0"
                @click="againClick"
                >再答一次</el-button
              >
              <!-- <el-button size="small" type="primary" @click="viewExam"
            >查看试卷</el-button
          > -->
            </div>
          </div>
        </div>
        <div
          v-if="isOvertime === '0' && isHasAnswer === '0'"
          class="overTimeClass"
        >
          <div class="module">
            <h2>
              {{ examConfig.testName }}
            </h2>
            <div class="fontSize13">
              {{ examConfig.startTime }}至{{ examConfig.endTime }}
            </div>
            <h1>考试已经结束</h1>
            <div>
              <el-button type="primary" @click="examSave(true)">交卷</el-button>
            </div>
            <div style="color: #4f8eff; line-height: 40px; font-size: 13px">
              你已经超过答题时长，请提交试卷
            </div>
          </div>
        </div>
      </template>
      <template v-if="!isStart && !isLimit">
        <div class="overTimeClass">
          <div class="module">
            <h2>
              {{ examConfig.testName }}
            </h2>
            <div class="fontSize13">
              {{ examConfig.startTime }}&nbsp;至&nbsp;{{ examConfig.endTime }}
            </div>
            <p v-if="timeRemaining !== ''" style="color: red">
              离考试结束还剩{{ timeRemaining }}分钟
            </p>
            <div class="examInfo">
              <div>
                <div style="font-weight: 800">
                  {{
                    examConfig.answerDuration > 0
                      ? examConfig.answerDuration
                      : "不限"
                  }}
                </div>
                <div class="fontSize13">时长(分钟)</div>
              </div>
              <div>
                <div style="font-weight: 800">{{ examConfig.subjectNum }}</div>
                <div class="fontSize13">题目量</div>
              </div>
              <div>
                <div style="font-weight: 800">{{ examConfig.totalScore }}</div>
                <div class="fontSize13">考试总分</div>
              </div>
            </div>
            <div>
              <template
                v-if="
                  new Date(this.serverTime).getTime() >
                  new Date(examConfig.startTime).getTime()
                "
              >
                <el-button type="primary" @click="startExam(true)"
                  >开始考试</el-button
                >
              </template>
              <template v-else>
                <el-button type="info" @click="startExam(false)"
                  >开始考试</el-button
                >
              </template>
            </div>
          </div>
        </div>
      </template>
      <template v-if="isLimit">
        <div class="overTimeClass">
          <div class="module">
            <h2>
              {{ examConfig.testName }}
            </h2>
            <div class="fontSize13">
              {{ examConfig.startTime }}&nbsp;至&nbsp;{{ examConfig.endTime }}
            </div>
            <h1>考试次数已达到上限</h1>
          </div>
        </div>
      </template>
    </template>
  </div>
</template>
<script>
import "@/styles/qsgCommon.scss";

import ExamViewCom from "@/components/examViewCom/index";
import { isNull } from "@/util/qsgCommon";
import { dateFormat } from "@/util/date";
import { Base64 } from "js-base64";
import { setStore, getStore, removeStore } from "@/util/store";
import { mapGetters } from "vuex";

import {
  getTestById,
  saveTest,
  saveUserCacheTest,
  getUserCacheTest,
  currentServerTime,
} from "@/api/exam/examDataAdd";
import { baseURL } from "@/api/common";

export default {
  inject: ["desktopWindow", "desktop"],

  name: "examDataAdd",
  components: {
    ExamViewCom,
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  props: {
    propParams: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      isLogo: true,
      resultData: {},
      isOvertime: "", // 默认空字符串，'0'超时，'1'没超时
      isHasAnswer: "", //默认空字符串，'0'local有存储数据，'1'没有存储数据
      isStartExam: false,
      isLimit: false,
      timeRemaining: "",
      realName: "",
      examLogo: require("@/assets/exam/startExamLogo.png"),
      isThank: false,
      isDetail: false,
      type: "add", // 是否预览试卷
      time: "00:00:00",
      titleImg: require("@/assets/exam/exam-book.png"),
      examFormKey: 1,
      examId: "",

      loadingBtn: false,

      examFormOption: {
        column: [],
        submitBtn: false,
        emptyBtn: false,
      },
      examFormData: {},
      examConfig: {
        examConfig: 0,
        testName: "",
      },

      captchaTag: false,
      captchaImg: "",
      captchaKey: "",

      captchaForm: {
        captchaValue: "",
      },
      currentTime: new Date().getTime(),
      serverTime: "",
      timeDown: null,
      timingData: null,
      isJurisdiction: true,
    };
  },
  methods: {
    // 答题form修改时
    formChange(val) {
      let itemOption = val;
      this.examFormOption.column.map((item) => {
        item.isActive = false;
        if (item.typeExam !== "htmlExam") {
          if (
            item.typeExam !== "inputExam" &&
            !this.validatenull(itemOption[item.prop])
          ) {
            item.isActive = true;
          }
          if (item.typeExam === "inputExam") {
            item.dicData.map((obj) => {
              if (!this.validatenull(itemOption[obj.value])) {
                item.isActive = true;
              }
            });
          }
        }
      });
      let formData = this.$refs.examFormRef.getData(false);
      if (this.type === "add") {
        removeStore({ name: this.userInfo.id });
        const copyStoreData = this.deepClone(this.examConfig);
        copyStoreData.frontAnswerJson = formData.saveJson.frontAnswerJson;
        setStore({
          name: this.userInfo.id,
          content: Base64.encode(JSON.stringify(copyStoreData)),
        });
        this.isHasAnswer = "0";
      }
      this.$forceUpdate();
    },
    // 答题卡序号
    resetIndexFun(prop, allColumn) {
      let res = '<i class="el-icon-warning" style="color: #f05050;"></i>';
      let tempColumn = allColumn.filter((item) => item.typeExam != "htmlExam");
      if (tempColumn.length > 0) {
        tempColumn.map((item, key) => {
          if (item.prop == prop) {
            res = key + 1;
          }
        });
      }
      return res;
    },
    // 开始考试
    startExam(flag) {
      if (flag) {
        this.isLogo = false;
        this.realName = getStore({ name: "userInfo" }).realName;
        this.isStart = true;
        if (this.type === "add" && this.isOvertime === "1") {
          this.examConfig.startExamTime = new Date().getTime();
          setStore({
            name: this.userInfo.id,
            content: Base64.encode(JSON.stringify(this.examConfig)),
          });
        } else {
          this.isHasAnswer = "1";
        }
        if (
          this.type === "add" &&
          new Date().getTime() < new Date(this.examConfig.endTime).getTime()
        ) {
          this.timeFun(this.examConfig);
          this.timingSave();
        }
        this.$forceUpdate();
      } else {
        if (this.isJurisdiction) {
          this.$message.warning("考试未开始，请耐心等待");
        }else{
          this.$message.warning('不在允许考试的权限里面')
        }
      }
    },
    async getActiveExam() {
      this.loadingBtn = true;
      if (this.propParams.examId) {
        this.examId = this.propParams.examId;
      } else if (this.desktop) {
        this.examId = this.desktopWindow.data.query.examId;
        if (!this.validatenull(this.desktopWindow.data.query.type)) {
          this.type = this.desktopWindow.data.query.type;
        }
      } else {
        this.examId = this.$route.query.examId;
        if (!this.validatenull(this.$route.query.type)) {
          this.type = this.$route.query.type;
        }
      }
      if (isNull(this.examId)) {
        this.$message.error("试卷参数设置错误。");
        return false;
      }

      const storeData = getStore({ name: this.userInfo.id });

      let copyStoreData = {},
        isPort = false;
      if (!this.validatenull(storeData)) {
        copyStoreData = this.deepClone(JSON.parse(Base64.decode(storeData)));
        this.examConfig = JSON.parse(Base64.decode(storeData));
        this.realName = getStore({ name: "userInfo" }).realName;
        if (
          new Date(copyStoreData.startTime).getTime() < new Date().getTime()
        ) {
          this.isStart = true;
        }
        // '0'超时 '1'没超时
        if (
          new Date().getTime() > new Date(copyStoreData.endTime).getTime() ||
          copyStoreData.publishStatus != 1
        ) {
          this.isOvertime = "0";
        } else {
          this.isOvertime = "1";
        }

        if (this.examId === copyStoreData.id && this.isOvertime === "1") {
          this.loadingBtn = false;
          if (isNull(copyStoreData.editorFrontJsonOfUser)) {
            this.$message.error("试卷问题设置错误。");
            this.loadingBtn = true;
          } else {
            this.examFormOption = JSON.parse(
              copyStoreData.editorFrontJsonOfUser
            );
            this.examFormOption.column.map((item) => {
              if (item.typeExam !== "htmlExam") {
                item.isActive = false;
              }
            });
            if (!this.validatenull(copyStoreData.frontAnswerJson)) {
              this.examFormData = JSON.parse(this.examConfig.frontAnswerJson);
            }
          }

          if (this.type === "add") {
            isPort = true;
            this.timeFun(copyStoreData);
            this.timingSave();
            this.isLogo = false;
          }

          this.examFormKey++;
        }
        //默认空字符串，'0'local有存储数据，'1'没有存储数据
        if (!this.validatenull(copyStoreData.frontAnswerJson)) {
          this.isHasAnswer = "0";
        } else {
          this.isHasAnswer = "1";
        }
      } else {
        this.isHasAnswer = "1";
        await getUserCacheTest({ testId: this.examId }).then((res) => {
          const storeData = res.data.data;
          if (!this.validatenull(res.data.data)) {
            isPort = true;
            copyStoreData = this.deepClone(
              JSON.parse(Base64.decode(storeData))
            );
            this.examConfig = JSON.parse(Base64.decode(storeData));
            this.realName = getStore({ name: "userInfo" }).realName;
            if (
              new Date(copyStoreData.startTime).getTime() < new Date().getTime()
            ) {
              this.isStart = true;
            }
            // '0'超时 '1'没超时
            if (
              new Date().getTime() >
                new Date(copyStoreData.endTime).getTime() ||
              copyStoreData.publishStatus != 1
            ) {
              this.isOvertime = "0";
            } else {
              this.isOvertime = "1";
            }

            if (this.examId === copyStoreData.id && this.isOvertime === "1") {
              this.loadingBtn = false;
              if (isNull(copyStoreData.editorFrontJsonOfUser)) {
                this.$message.error("试卷问题设置错误。");
                this.loadingBtn = true;
              } else {
                this.examFormOption = JSON.parse(
                  copyStoreData.editorFrontJsonOfUser
                );
                this.examFormOption.column.map((item) => {
                  if (item.typeExam !== "htmlExam") {
                    item.isActive = false;
                  }
                });
                if (!this.validatenull(copyStoreData.frontAnswerJson)) {
                  this.examFormData = JSON.parse(
                    this.examConfig.frontAnswerJson
                  );
                }
              }

              if (this.type === "add") {
                isPort = true;
                this.timeFun(copyStoreData);
                this.timingSave();
                this.isLogo = false;
              }
              this.examFormKey++;
            }
          } else {
            isPort = false;
          }
        });
      }
      if (this.examId !== copyStoreData.id || !isPort) {
        removeStore({ name: this.userInfo.id });
        await getTestById({
          operationType: 1,
          id: this.examId,
        })
          .then((res) => {
            const dataRes = res.data.data;
            this.isHasAnswer = "";
            this.examConfig = dataRes;
            this.loadingBtn = false;

            //是否开启验证码
            // this.captchaTag = dataRes.isCaptcha == 1 ? true : false;

            // this.getCaptcha();
            if (dataRes.limitStatus) {
              this.isLimit = true;
            }
            if (isNull(dataRes.editorFrontJsonOfUser)) {
              this.$message.error("试卷问题设置错误。");
              this.loadingBtn = true;
            } else {
              this.examFormOption = JSON.parse(dataRes.editorFrontJsonOfUser);
              this.examFormOption.column.map((item) => {
                if (item.typeExam !== "htmlExam") {
                  item.isActive = false;
                }
              });
            } // '0'超时 '1'没超时
            if (
              new Date().getTime() >
                new Date(this.examConfig.endTime).getTime() ||
              this.examConfig.publishStatus === 2
            ) {
              this.isOvertime = "0";
              this.isHasAnswer = "1";
            } else {
              this.isOvertime = "1";
            }
            if (dataRes.publishStatus != 1) {
              // this.$message.error("该试卷未发布，不能填写。");
              this.loadingBtn = true;
            }
            let endTime = new Date(dataRes.endTime).getTime(),
              nowTime = new Date().getTime(),
              timeDiff = endTime - nowTime;
            if (
              dataRes.answerDuration !== 0 &&
              timeDiff < dataRes.answerDuration * 60 * 1000
            ) {
              this.timeRemaining = Math.floor(timeDiff / 1000 / 60);
            } else {
              this.timeRemaining = "";
            }

            this.examFormKey++;
          })
          .catch(() => {
            this.isJurisdiction = false;
          });
      }
    },
    timeFun(data) {
      clearInterval(this.timeDown);
      let endTime = new Date(data.endTime).getTime(),
        nowTime = new Date().getTime(),
        timeDiff = endTime - nowTime;
      if (timeDiff < 0) {
        this.type = "";
        this.$message.error("考试时间已结束，不能进行考试！");
        return false;
      } else {
        if (
          data.answerDuration === 0 ||
          timeDiff < data.answerDuration * 60 * 1000
        ) {
          this.mistiming(timeDiff / 1000);
        } else {
          this.mistiming(data.answerDuration * 60);
        }
      }
    },
    sheetClick(id) {
      // document.getElementById(id).scrollIntoView();
      const mainElement = document.getElementById("ExamViewRightMain");
      const itemElement = document.getElementById(id);
      if (mainElement && itemElement) {
        // mainElement.scrollTop = itemElement.offsetTop; // 设置滚动位置到目标元素的顶部
        // 如果需要平滑滚动
        mainElement.scroll({ top: itemElement.offsetTop, behavior: "smooth" });
      } else {
        window.console.log(`未找到元素：#ExamViewRightMain 或 ${id}`);
      }
    },
    mistiming(timeStamp) {
      const _this = this;
      this.timeDown = setInterval(() => {
        if (timeStamp > 0) {
          timeStamp--;
          const newTime = this.formateTimeStamp(timeStamp);
          const str =
            "剩余时间：" +
            newTime.hour +
            ":" +
            newTime.min +
            ":" +
            newTime.seconds;
          _this.time = str;
        } else {
          clearInterval(this.timeDown);
          this.examSave(true);
        }
      }, 1000);
    },
    timingSave() {
      this.timingData = setInterval(() => {
        let formData = this.$refs.examFormRef.getData(false);
        const copyStoreData = this.deepClone(this.examConfig);
        copyStoreData.frontAnswerJson = formData.saveJson.frontAnswerJson;
        saveUserCacheTest({
          testId: this.examConfig.id,
          cacheUserTest: Base64.encode(JSON.stringify(copyStoreData)),
        }).then(() => {
          console.log("定时存储成功");
        });
      }, 300000);
    },
    formateTimeStamp(timeStamp) {
      // var day;
      let hour, min, seconds;

      // day = parseInt(timeStamp / (24 * 60 * 60)); // 计算整数天数
      // var afterDay = timeStamp - day * 24 * 60 * 60; // 取得算出天数后剩余的秒数
      hour = parseInt(timeStamp / (60 * 60)); // 计算整数小时数
      let afterHour = timeStamp - hour * 60 * 60; // 取得算出小时数后剩余的秒数
      min = parseInt(afterHour / 60); // 计算整数分
      seconds = parseInt(timeStamp - hour * 60 * 60 - min * 60); // 取得算出分后剩余的秒数

      // if (day < 10) {
      //   day = "0" + day;
      // }

      if (hour < 10) {
        hour = "0" + hour;
      }

      if (min < 10) {
        min = "0" + min;
      }

      if (seconds < 10) {
        seconds = "0" + seconds;
      }

      const restStamp = {
        // day: day,
        hour: hour,
        min: min,
        seconds: seconds,
      };
      return restStamp;
    },
    async examSave(flag) {
      let time = new Date().getTime(),
        timeDiff = 0,
        formData = { saveJson: {} };
      // 超时且local存有未提交的数据
      if (this.isOvertime === "0" && this.isHasAnswer === "0") {
        const storeData = getStore({ name: this.userInfo.id }),
          copyStoreData = this.deepClone(JSON.parse(Base64.decode(storeData)));
        this.examConfig = copyStoreData;
        formData = this.getSaveData(copyStoreData);
        this.currentTime = copyStoreData.startExamTime;
        timeDiff = time - this.currentTime;
      } else {
        timeDiff = time - this.currentTime;
        const diff = time - new Date(this.examConfig.startTime).getTime();
        if (!flag && this.examConfig.minAnswerDuration !== 0) {
          if (diff < this.examConfig.minAnswerDuration * 60 * 1000) {
            this.$message.error(
              "答题时间不得少于" + this.examConfig.minAnswerDuration + "分钟"
            );
            return false;
          }
        }

        let valiRes = true;

        if (this.captchaTag) {
          this.$refs.captchaRef.validate((boolean) => {
            valiRes = valiRes && boolean;
          });
        }
        if (this.examConfig.subjectNum > 0) {
          let inputValiRes = this.$refs.examFormRef.canInputValiRes();
          valiRes = valiRes && inputValiRes;

          let hasInputValiRes = this.$refs.examFormRef.hasInputValiRes();
          valiRes = valiRes && hasInputValiRes;

          this.$refs.examFormRef.$refs.formRef.validate((boolean) => {
            valiRes = valiRes && boolean;
          });
          if (!valiRes) {
            this.$message.error("试卷填写验证未通过，请检查！");
            this.loadingBtn = false;
            // this.getCaptcha();
            return false;
          }
        }
        formData = this.$refs.examFormRef.getData(true);
      }
      let frontAnswerJson = JSON.parse(formData.saveJson.frontAnswerJson),
        isBlank = false;
      if (!flag) {
        for (let key in frontAnswerJson) {
          if (key !== "examTitle" && key !== "examRemark") {
            if (this.validatenull(frontAnswerJson[key])) {
              isBlank = true;
            }
          }
        }
      }
      const dataParam = {
        ...formData.saveJson,
        doTime: Number((timeDiff / 1000).toFixed(0)),
        startTime: dateFormat(this.currentTime),
        endTime: dateFormat(time),
        // validateKey: this.captchaKey,
        // validateValue: this.captchaForm.captchaValue,
      };
      if (isBlank) {
        this.$confirm("还有未答完的试题确定要提交吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            clearInterval(this.timeDown);
            this.loadingBtn = true;
            saveTest(dataParam).then(
              (res) => {
                this.isLogo = true;
                const dataRes = res.data.success;
                this.resultData = res.data.data;
                removeStore({ name: this.userInfo.id });
                clearInterval(this.timingData);
                if (dataRes) {
                  if (this.examConfig.isDirectAfterFinish == 0) {
                    this.isThank = true;
                  } else if (this.examConfig.isDirectAfterFinish == 1) {
                    window.location.href = this.examConfig.directUrlAfterFinish;
                    this.loadingBtn = false;
                  }
                  if (this.isOvertime === "1") {
                    this.examReset();
                  }
                }
                this.type = "view";
                this.isHasAnswer = "1";
                this.timeRemaining = "";
              },
              (error) => {
                window.console.log(error);
                this.loadingBtn = false;
              }
            );
          })
          .catch(() => {
            window.console.log("操作已取消");
          });
      } else {
        clearInterval(this.timeDown);
        this.loadingBtn = true;

        saveTest(dataParam).then(
          (res) => {
            const dataRes = res.data.success;
            this.resultData = res.data.data;
            removeStore({ name: this.userInfo.id });
            clearInterval(this.timingData);
            if (dataRes) {
              this.isLogo = true;
              if (this.examConfig.isDirectAfterFinish == 0) {
                this.isThank = true;
              } else if (this.examConfig.isDirectAfterFinish == 1) {
                window.location.href = this.examConfig.directUrlAfterFinish;
                this.loadingBtn = false;
              }
              if (this.isOvertime === "1") {
                this.examReset();
              }
            }
            this.type = "view";
            this.isHasAnswer = "1";
            this.timeRemaining = "";
          },
          (error) => {
            window.console.log(error);
            this.loadingBtn = false;
          }
        );
      }
    },
    examReset() {
      this.$refs.examFormRef.onReset();
    },
    // 再答一次
    againClick() {
      this.$router.go(0);
    },
    // 查看试卷
    viewExam() {
      window.open(
        `${baseURL}#/exam/correctExam?id=` + this.resultData.id + "&type=view",
        "_self"
      );
    },
    getSaveData(data) {
      /*标准接口数据Json格式*/
      // this.$refs.doTimeRef.useTimeStop();
      // let editorFrontJsonOfUser = JSON.parse(deepClone(this.examConfig.editorFrontJsonOfUser))
      let VOArr = [],
        userInfo = getStore({ name: "userInfo" });
      let onlyOneJson = {};
      let formOption = JSON.parse(data.editorFrontJsonOfUser),
        formData = JSON.parse(data.frontAnswerJson);
      formOption.column.map((item /*,key*/) => {
        //console.log(this.formData[item.prop]);
        //处理身份验证类字段
        if (item.onlyOne) {
          onlyOneJson[item.prop] = formData[item.prop];
        }
        let cumItem = {
          questionnaireId: data.questionnaireId,
          questionnaireName: data.questionnaireName,
          subjectId: item.prop,
          subjectName: item.label,
          scoreType: item.scoringRule,
          testId: data.id,
          testName: data.testName,
          totalScore: item.score,
        };
        let extItem = {};

        switch (item.typeExam) {
          case "radioExam":
            extItem = {
              subjectType: 1,
              answersText: JSON.stringify([{ answer: formData[item.prop] }]),
              // this.getSelectOption(this.formData[item.prop], item)
              //   .answersText + "",
            };

            VOArr.push({ ...cumItem, ...extItem });
            break;

          case "rateExam":
            /*评分题 按照单选题 做数据存储，可以做数据统计*/
            extItem = {
              subjectType: 1,
              optionId: item.prop + "_Rm_rateOption_" + formData[item.prop],
              optionName: formData[item.prop],
              answersText: formData[item.prop] + "",
              optionSort: formData[item.prop],
              optionType: 1,
            };

            VOArr.push({ ...cumItem, ...extItem });
            break;

          case "checkboxExam":
            if (formData[item.prop]) {
              let arr = [];
              extItem = {
                subjectType: 2,
              };
              formData[item.prop].map((info /*,ind*/) => {
                arr.push({ answer: info });
              });
              extItem.answersText = JSON.stringify(arr);
              VOArr.push({ ...cumItem, ...extItem });
            }
            break;

          case "estimateExam":
            extItem = {
              subjectType: 3,
              answersText: JSON.stringify([{ answer: formData[item.prop] }]),
              // this.getSelectOption(this.formData[item.prop], item)
              //   .optionName + "",
            };

            VOArr.push({ ...cumItem, ...extItem });
            break;

          case "inputExam":
            if (!isNull(item.dicData)) {
              let arr = [];
              extItem = {
                subjectType: 4,
              };
              formData[item.prop] = "";
              item.dicData.map((obj) => {
                if (!this.validatenull(formData[obj.value])) {
                  arr.push({
                    answer: formData[obj.value].replace(/\s/g, ""),
                  });
                  formData[item.prop] +=
                    formData[obj.value].replace(/\s/g, "") + ",";
                }
              });
              extItem.answersText = JSON.stringify(arr);
              VOArr.push({ ...cumItem, ...extItem });
            }

            break;
          case "textareaExam":
            extItem = {
              subjectType: 5,
              optionType: 3,
              //answerQuestionnaireId: item.prop,
              answersText: JSON.stringify([{ answer: formData[item.prop] }]),
            };
            VOArr.push({ ...cumItem, ...extItem });
            break;

          case "uploadExam":
            extItem = {
              subjectType: 6,
              optionType: 3,
              answersText: JSON.stringify(formData[item.prop]) + "",
            };
            VOArr.push({ ...cumItem, ...extItem });
            break;
          default:
            extItem = {
              subjectType: 6,
              optionType: 3,
              answersText: formData[item.prop] + "",
            };
            VOArr.push({ ...cumItem, ...extItem });
        }
      });
      //将未选中的可填项的值 剔除
      const resFormData = this.deepClone(formData);
      for (let key in resFormData) {
        if (key.includes("_Rm_")) {
          const subKey = key.split("_Rm_")[0];
          if (!resFormData[subKey].includes(key)) {
            delete resFormData[key];
          }
        }
      }
      const saveJson = {
        frontAnswerJson: JSON.stringify({ ...resFormData }),
        editorFrontJsonOfUser: data.editorFrontJsonOfUser,
        questionnaireId: data.questionnaireId,
        questionnaireName: data.questionnaireName,
        answerTestSubjects: VOArr,
        testId: data.id,
        testName: data.testName,
        totalScore: data.totalScore,
        realName: userInfo.realName,
        subjectNum: data.subjectNum,
        ...onlyOneJson,
      };

      const res = {
        ExamData: { ...resFormData },
        // ExamOption: { ...this.option },
        saveJson: { ...saveJson },
      };
      return res;
    },

    // getCaptcha(){

    //   this.captchaValue ='';

    //   if(this.captchaTag){
    //     getExamCaptcha().then((res) => {
    //       const dataRes = res.data.data;
    //       this.captchaImg = dataRes.image;
    //       this.captchaKey = dataRes.key;

    //     }, error => {
    //       window.console.log(error);
    //     });
    //   }

    // },
  },
  mounted() {
    this.getActiveExam();
    // const _this = this;
    // this.$refs.doTimeRef.useTimeStop();
    // this.$refs.doTimeRef.useTimeStart(true);
    this.$nextTick(() => {
      // 打开右键
      document.oncontextmenu = new Function("event.returnValue=false");
      // 打开选择
      document.onselectstart = new Function("event.returnValue=false");
      //   // 打开F12
      document.onkeydown = () => {
        if (window.event && window.event.keyCode == 123) {
          return false;
        }
        if (window.event.shiftKey && window.event.keyCode == 121) {
          return false;
        }
        //禁用ctrl + v 功能
        // if (window.event.ctrlKey && window.event.keyCode == 86) {
        //   return false;
        // }
        if (
          window.event.ctrlKey &&
          window.event.shiftKey &&
          window.event.keyCode == 73
        ) {
          return false;
        }
      };
    });
  },
  created() {
    currentServerTime().then((res) => {
      if (res.data.success) {
        this.serverTime = res.data.data;
      }
    });
  },
  destroyed() {
    document.onkeydown = () => {
      if (window.event && window.event.keyCode == 123) {
        return true;
      }
      if (window.event.shiftKey && window.event.keyCode == 121) {
        return true;
      }
      if (
        window.event.ctrlKey &&
        window.event.shiftKey &&
        window.event.keyCode == 73
      ) {
        return true;
      }
    };
    document.onselectstart = new Function("event.returnValue=true");
    document.oncontextmenu = new Function("event.returnValue=true");
  },
  watch: {
    $route: "getActiveExam",
    "desktopWindow.data": {
      handler() {
        this.getActiveExam();
      },
      deep: true,
    },
    propParams: {
      handler() {
        this.getActiveExam();
      },
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.ExamViewMain {
  width: 100%;
  height: 100%;
  background-image: url("~@/assets/exam/exambg.jpg");
  background-size: cover;
  // background-color: #f5f5f5;
  // overflow-y: auto;

  .logo {
    position: fixed;
    left: 100px;
    top: 60px;
  }
  .overTimeClass {
    width: 100%;
    height: 100%;

    .module {
      position: fixed;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 600px;
      text-align: center;
      margin: 0 auto;
      display: flex;
      background-color: #fff;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 30px;
      border-radius: 8px;
      box-shadow: -1px 5px 26px 5px #d3d3d3;
      .examInfo {
        width: 100%;
        display: flex;
        align-items: center;
        padding: 25px 0px;
        justify-content: space-between;
      }
      .fontSize13 {
        color: darkgray;
        font-size: 13px;
      }
    }
  }
}
.ExamViewBody {
  // max-width: 1000px;
  min-height: 100%;
  margin: 0 auto;
  padding: 0px !important;
  background-color: #e9ebee;
  border-left: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .examTop {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #2b3643;
    line-height: 50px;
    color: #fff;
    padding: 0 15px;
    margin-bottom: 20px;
    .examUseTime {
      margin-right: 15px;
    }
    .blockStyle {
      margin-right: 15px;
      background-color: #364150;
      color: #fff;
      height: 35px;
      font-size: 14px;
      line-height: 35px;
      padding: 0 15px;
      border-radius: 5px;
    }
  }
  .examContent {
    display: flex;
    align-items: flex-start;
    justify-content: space-around;
    padding: 0px 15px;
    .left {
      width: 350px;
      background-color: #fff;
      border-radius: 10px;
      padding: 20px;
      padding-right: 0px;
    }
    .right {
      width: calc(100% - 370px);
      background-color: #fff;
      border-radius: 10px;
      padding: 20px;
      padding-right: 0px;
    }
  }
  .answerSheet {
    text-align: center;
    height: calc(100vh - 120px);
    overflow-y: auto;
    .sheetContent {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      align-items: center;
      color: #c7cad3;
      .indexStyle {
        width: 53px;
        height: 53px;
        line-height: 60px;
        background-color: #f4f5f7;
        margin: 0px 9px 9px 0;
        border-radius: 5px;
        cursor: pointer;
      }
    }
    .colorContent {
      display: flex;
      justify-content: space-around;
      align-items: center;
      > div {
        display: flex;
        justify-content: space-around;
        align-items: center;
      }
      .colorBlock {
        width: 18px;
        height: 18px;
        border-radius: 2px;
        margin-right: 10px;
      }
    }
  }
  .ExamView {
    height: calc(100vh - 120px);
    overflow-y: auto;
    padding-right: 20px;
    a {
      text-decoration: underline;
      color: #0045c8;
    }
  }
  .employe {
    padding: 40px 0;
    text-align: center;
    background-color: #ffffff;
    border-radius: 10px;
    color: #c7cad3;
    font-size: 14px;
    height: calc(100vh - 100px);
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-content: center;
    align-items: center;

    .employeImg {
      width: 150px;
      width: 150px;
    }
  }
  .thankModule {
    background-color: #fff;
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}
.ExamViewBtn {
  text-align: center;
  display: flex;
  align-items: center;
}
.cusSet {
  .captchaForm {
    border-top: 2px solid #e4e7ed;
    padding-top: 15px;
    .captchaItem {
      .captchaContent {
        display: flex;

        .captchaInput {
          width: 180px;
          max-width: 300px;
        }
        .captchaRight {
          display: flex;
          .captchaImg {
            height: 40px;
            margin-left: 10px;
            margin-right: 10px;
          }
        }
      }
    }
  }
}
</style>
